package com.rayson.oneapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rayson.oneapi.constant.UserConstant;
import com.rayson.oneapi.exception.BusinessException;
import com.rayson.oneapi.mapper.UserMapper;
import com.rayson.oneapi.model.entity.User;
import com.rayson.oneapi.model.enums.ErrorCode;
import com.rayson.oneapi.model.enums.UserRoleEnum;
import com.rayson.oneapi.model.req.user.*;
import com.rayson.oneapi.model.vo.LoginUserVO;
import com.rayson.oneapi.model.vo.UserVO;
import com.rayson.oneapi.service.UserService;
import com.rayson.oneapi.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.rayson.oneapi.constant.UserConstant.USER_LOGIN_STATE;


/**
 * 用户服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userRegister(UserRegisterRequest userRegisterRequest) {
        // 密码和校验密码相同
        if (!userRegisterRequest.isPasswordSame()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        String username = userRegisterRequest.getUsername();
        synchronized (username.intern()) {
            // 账户不能重复
            LambdaQueryWrapper<User> queryWrapper = lambdaQuery().getWrapper()
                    .eq(User::getUsername, username);
            long count = this.count(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + userRegisterRequest.getPassword()).getBytes());
            // 3. 插入数据
            User user = User.initUser(username, encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
        }
    }

    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        String password = userLoginRequest.getPassword();
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + password).getBytes());
        // 查询用户是否存在
        LambdaQueryWrapper<User> queryWrapper = lambdaQuery().getWrapper()
                .eq(User::getUsername, userLoginRequest.getUsername())
                .eq(User::getPassword, encryptPassword);
        User user = this.getOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 判断用户是否被禁用
        if (UserRoleEnum.BAN.getValue().equals(user.getUserRole())) {
            log.info("用户{}被禁止登录", user.getUsername());
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已被禁止登录");
        }
        // 4. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        String userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前登录用户（允许未登录）
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        String userId = currentUser.getId();
        return this.getById(userId);
    }

    /**
     * 是否为管理员
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 用户注销
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(request.getNickName()), "nick_name", request.getNickName())
                .like(StringUtils.hasText(request.getUserProfile()), "user_profile", request.getUserProfile())
                .like(StringUtils.hasText(request.getUserRole()), "user_role", request.getUserRole());
        return queryWrapper;
    }

    @Override
    public void addUser(UserAddRequest userAddRequest) {
        // 校验用户名唯一性
        LambdaQueryWrapper<User> queryWrapper = lambdaQuery().getWrapper().eq(User::getUsername, userAddRequest.getUsername());
        User userInDb = getOne(queryWrapper);
        if (userInDb != null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户名已存在");
        }
        String encryptPassword = DigestUtils.md5DigestAsHex((UserConstant.PASSWORD_SALT + UserConstant.DEFAULT_PASSWORD).getBytes());
        User user = User.initUser(userAddRequest.getUsername(), encryptPassword, userAddRequest.getUserRole());
        this.save(user);
    }

    @Override
    public void updateUser(UserUpdateRequest userUpdateRequest) {
        LambdaUpdateWrapper<User> updateWrapper = lambdaUpdate().getWrapper()
                .eq(User::getId, userUpdateRequest.getId())
                .set(StringUtil.hasText(userUpdateRequest.getNickName()), User::getNickName, userUpdateRequest.getNickName())
                .set(StringUtil.hasText(userUpdateRequest.getUserProfile()), User::getUserProfile, userUpdateRequest.getUserProfile())
                .set(StringUtil.hasText(userUpdateRequest.getUserRole()), User::getUserRole, userUpdateRequest.getUserRole())
                .set(StringUtil.hasText(userUpdateRequest.getUserAvatar()), User::getUserAvatar, userUpdateRequest.getUserAvatar());
        this.update(updateWrapper);
    }

    @Override
    public void updateUserBySelf(UserUpdateMyRequest userUpdateMyRequest, HttpServletRequest request) {
        User loginUser = this.getLoginUser(request);
        LambdaUpdateWrapper<User> updateWrapper = lambdaUpdate().getWrapper()
                .eq(User::getId, loginUser.getId())
                .set(StringUtil.hasText(userUpdateMyRequest.getNickName()), User::getNickName, userUpdateMyRequest.getNickName())
                .set(StringUtil.hasText(userUpdateMyRequest.getUserProfile()), User::getUserProfile, userUpdateMyRequest.getUserProfile())
                .set(StringUtil.hasText(userUpdateMyRequest.getUserAvatar()), User::getUserAvatar, userUpdateMyRequest.getUserAvatar());
        this.update(updateWrapper);
    }
}
